package com.otomotion.research.ants.entities;

import com.otomotion.research.ants.information.Coordinate;
import com.otomotion.research.ants.information.Information;
import com.otomotion.research.ants.information.AntType;
import com.otomotion.research.ants.request.DropRequest;
import com.otomotion.research.ants.request.MoveRequest;
import com.otomotion.research.ants.request.PickUpRequest;
import com.otomotion.research.ants.request.Request;

import gnu.cajo.invoke.Remote;

import java.util.Random;
import java.util.Vector;

import org.jdom.Document;
import org.jdom.output.XMLOutputter;

/**
 * @author    joel
 */
public class Ant extends Entity
{
    Coordinate location = null;
    Object payload;
    AntType type;
    String subType;

    static Object antBrain;

    private void reconnect()
    {
        String hostname = "E00110A9B4B76.eamcs.ericsson.se";
        int port = 9999;
        try {
            System.out.println("Connecting to brain at host " + hostname
                    + " on port " + port);
            antBrain = Remote.getItem("//" + hostname + ":" + port
                    + "/brainServer");

            System.out.println("Connected!");
        } catch (Exception e) {

            e.printStackTrace();
        }
    }
    public Ant()
    {
        if (antBrain==null)
        {
            reconnect();
        }
        type = AntType.SCOUT;
        subType = "basic";

    }

    public Request getNextRequest(Information info)
    {
        Request req = null;
        //make remote request for instruction
        try {


            req = (Request) Remote.invoke(antBrain,
                    "getRequest", info);


        } catch (Exception e) {

            System.out.println("could not reach brain, will randomize.");
        }

        if (req!=null)
            return req;

        Coordinate here = new Coordinate(0,0,0);
        Vector v = Coordinate.getTwentySevenAdjacentCoordinates(here);
        Random r = new Random();
        int i = r.nextInt(v.size());
        int request = r.nextInt(3);
        if (request==0)
            return new MoveRequest((Coordinate)v.elementAt(i));
        if (request==1)
            return new PickUpRequest((Coordinate)v.elementAt(i));
        if (request==2)
            return new DropRequest((Coordinate)v.elementAt(i));
        return null;


    }

    public Coordinate getLocation()
    {
        return location;
    }

    public void setLocation(Coordinate location)
    {
        this.location = location;
    }

    public boolean setPayload(Object o)
    {
        if (payload==null)
            this.payload = o;
        else
            return false;
        return true;

    }

    public Object getPayload()
    {
        return payload;
    }



}
